/*
    This file is part of jTopaz.
    http://gcl.cis.udel.edu/projects/jtopaz
    Copyright (C) 2009 University of Delaware

    jTopaz is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    jTopaz is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of                                                        
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with jTopaz.  If not, see <http://www.gnu.org/licenses/>.
*/
var regFile;
var regList;
var menu;

var consoleService = Components.classes['@mozilla.org/consoleservice;1']
                               .getService(Components.interfaces.nsIConsoleService);
var prefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
function init( )
{
	    try{
      	
				var prefs = prefService.getBranch("extensions.topaz.");
				var initial = prefs.getCharPref( "gama.url" );
				dump("initial: " + initial + "\n");				
				if( initial != ""){
					dump("Entered if\n");
					var setUrl = document.getElementById( "gama-url" );
					setUrl.setAttribute ( "value", initial );
				}
				else {
				
					var regFile;
			  	var profDir = Components.classes["@mozilla.org/file/directory_service;1"]
							          .getService(Components.interfaces.nsIProperties)
							          .get("ProfD", Components.interfaces.nsILocalFile);
			  	profDir.append( "topaz" );
			  	profDir.append( "gama-hosts.xml" );
			  	var regFile = new File( profDir );

			  	if( !regFile.exists( ) )
			  	{
		      	regFile.create( );
			  	}
			  	regFile.open( "r" );
  		  	var regList = new XML( regFile.read( ) );
			  	regFile.close( );
													
  				var locations = regList..location;
  				var i = locations.length()-1;
					if( locations[i] != "")
					{
						var setUrl = document.getElementById( "gama-url" );
						setUrl.setAttribute ( "value", locations[i] );
					}
				}
			}catch( e ){};
}

function addListing( evt )
{

    try{
  var regFile;
  var profDir = Components.classes["@mozilla.org/file/directory_service;1"]
          .getService(Components.interfaces.nsIProperties)
          .get("ProfD", Components.interfaces.nsILocalFile);
  profDir.append( "topaz" );
	profDir.append( "gama-hosts.xml" );
	var regFile = new File( profDir );

  if( !regFile.exists( ) )
  {
      regFile.create( );
  }

  var listing = document.getElementById( "gama-url" ).value;

  regFile.open( "r" );
  var regList = new XML( regFile.read( ) );
  regFile.close( );

  //if( regList.elements( ).length( ) == 0 )
  if( (regList == null) || ( regList.elements().length( ) == 0 ) )
  {
      regList = <registryList />;
  }

  listing = listing.replace( /\s/g , "" );
  if( (listing != "" ) && !( /(chrome)|(Remove)/.test( listing ) ) )
  {
      var match =  regList.registry.(location == listing );

      if( match && (match.length( ) == 0 ) )
      {
        regList.appendChild( <registry><location>{listing}</location></registry> );
        regFile.open(  "w" );
        regFile.write( regList.toXMLString( ) );
        regFile.close( );
        changeGamaRegistry( listing );
      }
  }

    }catch( e ){ consoleService.logStringMessage( e ); }
}

function removeGamaListing( listing  )
{
    try{
  var regFile;
  var profDir = Components.classes["@mozilla.org/file/directory_service;1"]
          .getService(Components.interfaces.nsIProperties)
          .get("ProfD", Components.interfaces.nsILocalFile);
  profDir.append( "topaz" );
  profDir.append( "gama-hosts.xml" );
  var regFile = new File( profDir );

  if( !regFile.exists( ) )
  {
      regFile.create( );
  }

  regFile.open( "r" );
  var regList = new XML( regFile.read( ) );
  regFile.close( );

  try{
      var match =  regList.registry.(location == listing ).childIndex();
  }catch( e ){ match = -1 }
  if( match  > -1  )
  {
      delete regList.registry[ match ];
  }

  regFile.open( "w" );
  regFile.write( regList.toXMLString( ) );
  regFile.close( );

    }catch( e ){ consoleService.logStringMessage( e ); }
}

function doOK( )
{
    try{
			var sel = document.getElementById( "gama-url" ).value;
			window.arguments[0].newRegistry = sel;

      var prefs = prefService.getBranch("extensions.topaz.");
			prefs.setCharPref( "gama.url" , sel );
			
			var event;
			addListing( event );
    }catch( e ){ alert( e ); return true; }
    
		return true;
}


function doCancel( )
{
    return true;
}

function fillGama( )
{
    try{
  var regList;
  var regFile;
  var menu;
  menu = document.getElementById( "gama-menu" );

  var profDir = Components.classes["@mozilla.org/file/directory_service;1"]
          .getService(Components.interfaces.nsIProperties)
          .get("ProfD", Components.interfaces.nsILocalFile);

  profDir.append( "topaz" );
  profDir.append( "gama-hosts.xml" );
  regFile = new File( profDir );

  if( !regFile.exists( ) )
  {
      regFile.create( );
      return;
  }

  try{
        var length = menu.childNodes.length - 1;
        for( var i = length; i >= 0; i-- )
        {
      menu.removeChild( menu.childNodes.item( i ) );
        }
  }catch( e ){ }

  var menuItem = document.createElement( "menuitem" );

  regFile.open( "r" );
  regList = new XML(  regFile.read() );
  regFile.close();

  var locations = regList..location;
  for( var i = 0; i < locations.length( ); i++ )
  {
      var z = locations.length()-(i+1);  
			if( locations[ z ] == "" )
      continue;
        menuItem = document.createElement( "menuitem" );
        menuItem.setAttribute( "label", locations[ z ]   );
        menuItem.setAttribute( "value", locations[ z ]   );
        menu.appendChild(  menuItem );
  }
  menuItem = document.createElement( "menuseparator" );
  menu.appendChild(  menuItem );
  menuItem = document.createElement( "menuitem" );
  menuItem.setAttribute( "label",  "Remove Current Registry" );
  menuItem.setAttribute( "value",  "Remove Current Registry" );
  menu.appendChild(  menuItem );

    }catch( e ){  }
}

function changeGamaRegistry( val, event )
{

  try{
    var newValue;
    if( val )
        newValue =  val;
    else
    {
        try{
      newValue =  event.target.value;
        }catch( e ){ newValue = document.getElementById("gama-url" ).value;  }
    }


    newValue = newValue.replace( /\s/g , "" );
    if( newValue != "" )
    {
        if( (newValue.search( "Remove" ) != -1) && (newValue.search( "chrome" ) == -1) )
        {
      removeGamaListing( document.getElementById( "gama-url" ).value );
      newValue = "";
        }
         var prefs = prefService.getBranch("extensions.topaz.");
         prefs.setCharPref( "gama.url" , newValue );
         document.getElementById("gama-url" ).value = newValue;
    }

  }catch( e ){ alert( e ); }
}